import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import resnet50


class SimCLRStage1(nn.Module):
    def __init__(self, feature_dim=128):
        super(SimCLRStage1, self).__init__()
        self.f = []
        for name, module in resnet50().named_children():
            if name == "conv1":
                module = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
            if not isinstance(module, nn.Linear) and not isinstance(module, nn.MaxPool2d):
                # 去掉池化层及全连接层
                self.f.append(module)
        # encoder
        self.f = nn.Sequential(*self.f)
        # projection head
        """
        依次进行全连接、批次标准化、relu激活、全连接，得到输出特征
        """
        self.g = nn.Sequential(
            nn.Linear(2048, 512, bias=False),
            nn.BatchNorm1d(512),
            nn.ReLU(inplace=True),
            nn.Linear(512, feature_dim, bias=True)
        )

    def forward(self, x):
        x = self.f(x)
        feature = torch.flatten(x, start_dim=1)  # 将特征图平坦化
        out = self.g(feature)
        return F.normalize(feature, dim=-1), F.normalize(out, dim=-1)


class SimCLRStage2(nn.Module):
    def __init__(self, num_class):
        super(SimCLRStage2, self).__init__()
        # encoder
        self.f = SimCLRStage1().f
        # classifier
        self.fc = nn.Linear(2048, num_class, bias=True)

        for param in self.f.parameters():
            param.requires_grad = False

    def forward(self, x):
        x = self.f(x)
        feature = torch.flatten(x, start_dim=1)
        out = self.fc(feature)
        return out


class Loss(nn.Module):
    def __init__(self):
        super(Loss, self).__int__()

    def forward(self, out1, out2, batch_size, temperature=0.5):
        out = torch.cat([out1, out2], dim=0)
        sim_matrix = torch.exp(torch.Tensor(torch.mm(out, out.t()) / temperature))
        mask = (torch.ones_like(sim_matrix) - torch.eye(2 * batch_size, device=sim_matrix.device)).bool()
        sim_matrix = sim_matrix.masked_select(mask).view(2 * batch_size, -1)

        pos_sim = torch.exp(torch.Tensor(torch.sum(out1 * out2, dim=-1) / temperature))
        pos_sim = torch.cat([pos_sim, pos_sim], dim=0)
        return (-torch.log(pos_sim / sim_matrix.sum(dim=-1))).mean()
